using UnityEngine;
using System.Collections.Generic;
using System.Linq;

/// <summary>
/// Gizmos控制面板 - 统一管理所有可视化开关
/// </summary>
public class GizmosControlPanel : MonoBehaviour
{
    public static GizmosControlPanel Instance;

    [Header("面板设置")]
    [Tooltip("是否显示控制面板")]
    public bool showPanel = true;
    
    [Tooltip("面板显示开关（快捷键：G）")]
    public bool panelVisible = true;
    
    [Tooltip("面板位置")]
    public Vector2 panelPosition = new Vector2(10, 10);
    
    [Tooltip("面板大小")]
    public Vector2 panelSize = new Vector2(300, 600);

    [Header("网格可视化")]
    [Tooltip("显示网格边缘")]
    public bool showGridEdges = true;
    
    [Tooltip("显示网格中心点")]
    public bool showGridCenters = true;
    
    [Tooltip("显示熵值数值")]
    public bool showEntropyValues = false;
    
    [Tooltip("显示点阵")]
    public bool showDotGrid = false;

    [Header("无人机可视化")]
    [Tooltip("显示扫描范围")]
    public bool showScanRange = true;
    
    [Tooltip("显示排斥力范围")]
    public bool showRepulsionRange = false;
    
    [Tooltip("显示方向向量")]
    public bool showDirectionVectors = true;
    
    [Tooltip("显示运动拖尾")]
    public bool showTrail = true;

    [Header("Leader可视化")]
    [Tooltip("显示Leader范围")]
    public bool showLeaderRange = true;
    
    [Tooltip("显示Leader轨迹")]
    public bool showLeaderTrajectory = true;

    [Header("统计面板")]
    [Tooltip("是否显示统计面板")]
    public bool showStatsPanel = true;
    
    private bool isInitialized = false;
    private Rect windowRect;
    private Rect statsWindowRect;
    private Vector2 scrollPosition;

    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else if (Instance != this)
        {
            Destroy(gameObject);
        }
    }

    private void Start()
    {
        windowRect = new Rect(panelPosition.x, panelPosition.y, panelSize.x, panelSize.y);
        statsWindowRect = new Rect(10, Screen.height - 250, 400, 240);
        isInitialized = true;
    }

    private void Update()
    {
        // 按G键切换面板显示
        if (Input.GetKeyDown(KeyCode.G))
        {
            panelVisible = !panelVisible;
        }
        
        // 实时同步拖尾开关到所有AutoScanner
        SyncTrailSettings();
    }
    
    private void SyncTrailSettings()
    {
        // 同步拖尾开关到所有AutoScanner
        var scanners = FindObjectsOfType<AutoScanner>();
        foreach (var scanner in scanners)
        {
            if (scanner != null)
            {
                scanner.enableTrail = showTrail;
            }
        }
    }

    private void OnGUI()
    {
        if (!isInitialized) return;
        
        // 绘制控制面板
        if (showPanel && panelVisible)
        {
            windowRect = GUILayout.Window(999, windowRect, DrawControlPanel, "Gizmos控制面板 (按G隐藏)");
            windowRect.x = Mathf.Clamp(windowRect.x, 0, Screen.width - windowRect.width);
            windowRect.y = Mathf.Clamp(windowRect.y, 0, Screen.height - windowRect.height);
        }
        
        // 绘制统计面板
        if (showStatsPanel && panelVisible)
        {
            statsWindowRect = GUILayout.Window(998, statsWindowRect, DrawStatsPanel, "统计信息");
            statsWindowRect.x = Mathf.Clamp(statsWindowRect.x, 0, Screen.width - statsWindowRect.width);
            statsWindowRect.y = Mathf.Clamp(statsWindowRect.y, 0, Screen.height - statsWindowRect.height);
        }
    }

    private void DrawControlPanel(int windowID)
    {
        // 使用自定义样式
        var boldLabelStyle = new GUIStyle(GUI.skin.label) { fontStyle = FontStyle.Bold };
        
        GUILayout.BeginVertical("box");
        
        // 滚动区域
        scrollPosition = GUILayout.BeginScrollView(scrollPosition);
        
        // 网格可视化
        GUILayout.Label("网格可视化", boldLabelStyle);
        showGridEdges = GUILayout.Toggle(showGridEdges, "显示网格边缘");
        showGridCenters = GUILayout.Toggle(showGridCenters, "显示网格中心点");
        showEntropyValues = GUILayout.Toggle(showEntropyValues, "显示熵值数值");
        showDotGrid = GUILayout.Toggle(showDotGrid, "显示点阵");
        
        GUILayout.Space(10);
        
        // 无人机可视化
        GUILayout.Label("无人机可视化", boldLabelStyle);
        showScanRange = GUILayout.Toggle(showScanRange, "显示扫描范围");
        showRepulsionRange = GUILayout.Toggle(showRepulsionRange, "显示排斥力范围");
        showDirectionVectors = GUILayout.Toggle(showDirectionVectors, "显示方向向量");
        showTrail = GUILayout.Toggle(showTrail, "显示运动拖尾");
        
        GUILayout.Space(10);
        
        // Leader可视化
        GUILayout.Label("Leader可视化", boldLabelStyle);
        showLeaderRange = GUILayout.Toggle(showLeaderRange, "显示Leader范围");
        showLeaderTrajectory = GUILayout.Toggle(showLeaderTrajectory, "显示Leader轨迹");
        
        GUILayout.Space(10);
        
        // 批量控制
        GUILayout.Label("批量控制", boldLabelStyle);
        GUILayout.BeginHorizontal();
        if (GUILayout.Button("全部显示"))
        {
            SetAllVisible(true);
        }
        if (GUILayout.Button("全部隐藏"))
        {
            SetAllVisible(false);
        }
        GUILayout.EndHorizontal();
        
        GUILayout.EndScrollView();
        
        GUILayout.EndVertical();
        
        // 使窗口可拖拽
        GUI.DragWindow();
    }

    private void SetAllVisible(bool visible)
    {
        showGridEdges = visible;
        showGridCenters = visible;
        showEntropyValues = visible;
        showDotGrid = visible;
        showScanRange = visible;
        showRepulsionRange = visible;
        showDirectionVectors = visible;
        showTrail = visible;
        showLeaderRange = visible;
        showLeaderTrajectory = visible;
    }
    
    private void DrawStatsPanel(int windowID)
    {
        var boldLabelStyle = new GUIStyle(GUI.skin.label) { fontStyle = FontStyle.Bold };
        
        GUILayout.BeginVertical("box");
        
        // 熵值统计
        if (OptimizedHexGrid.Instance != null)
        {
            GUILayout.Label("网格熵值统计", boldLabelStyle);
            
            var cells = OptimizedHexGrid.Instance.allCells;
            if (cells != null && cells.Count > 0)
            {
                // 计算统计信息
                float totalEntropy = 0f;
                float minEntropy = float.MaxValue;
                float maxEntropy = float.MinValue;
                int scannedCount = 0;
                const float scannedThreshold = 30f;
                
                foreach (var cell in cells)
                {
                    totalEntropy += cell.entropy;
                    if (cell.entropy < minEntropy) minEntropy = cell.entropy;
                    if (cell.entropy > maxEntropy) maxEntropy = cell.entropy;
                    if (cell.entropy < scannedThreshold) scannedCount++;
                }
                
                float avgEntropy = totalEntropy / cells.Count;
                float scanRatio = (float)scannedCount / cells.Count * 100f;
                
                GUILayout.Label($"总单元数: {cells.Count}");
                GUILayout.Label($"已扫描: {scannedCount} ({scanRatio:F1}%)");
                GUILayout.Label($"平均熵值: {avgEntropy:F1}");
                GUILayout.Label($"最大熵值: {maxEntropy:F1}");
                GUILayout.Label($"最小熵值: {minEntropy:F1}");
            }
            else
            {
                GUILayout.Label("无网格数据");
            }
            
            GUILayout.Space(10);
        }
        
        // 无人机统计
        var scanners = FindObjectsOfType<AutoScanner>();
        if (scanners != null && scanners.Length > 0)
        {
            GUILayout.Label("无人机统计", boldLabelStyle);
            GUILayout.Label($"无人机数量: {scanners.Length}");
            
            foreach (var scanner in scanners)
            {
                if (scanner != null)
                {
                    GUILayout.Label($"• {scanner.UavName}: 活跃");
                }
            }
            
            GUILayout.Space(10);
        }
        else
        {
            GUILayout.Label("无人机统计", boldLabelStyle);
            GUILayout.Label("无人机数量: 0");
            GUILayout.Space(10);
        }
        
        // Leader统计
        if (LeaderController.Instance != null)
        {
            GUILayout.Label("Leader统计", boldLabelStyle);
            GUILayout.Label($"扫描半径: {LeaderController.Instance.scanRadius:F1}m");
            GUILayout.Label($"移动速度: {LeaderController.Instance.moveSpeed:F3}m/s");
            GUILayout.Label($"运行状态: {(LeaderController.Instance.IsStart ? "进行中" : "等待")}");
        }
        
        GUILayout.EndVertical();
        
        // 使窗口可拖拽
        GUI.DragWindow();
    }
}

